package com.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientTest {

	public static void main(String[] args) {

//		ApplicationContext context = new ClassPathXmlApplicationContext("classpath:httpclientContext.xml");
//
//		HttpComponentsClientHttpRequestFactory factory = (HttpComponentsClientHttpRequestFactory) context
//				.getBean("clientHttpRequestFactory");
//
//		try {
//			for (int i = 0; i < 10; i++) {
//				HttpPost post = new HttpPost("http://test.anxinyisheng.com/home/apiInternal/qaCtypes");
//				HttpResponse resp = factory.getHttpClient().execute(post);
//				HttpEntity entity = resp.getEntity();
//				entity = new BufferedHttpEntity(entity);
//				System.out.println(EntityUtils.toString(entity));
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		HttpClientTest client = new HttpClientTest();
		client.pp();
	}

	public void post() {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("param1", "value1"));
		formparams.add(new BasicNameValuePair("param2", "value2"));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		HttpPost httppost = new HttpPost("http://localhost/handler.do");
		httppost.setEntity(entity);
	}

	public void pp() {

		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet("http://localhost:9200/axdoc/question/_search?q=acontent:我感冒了");
		CloseableHttpResponse resp = null;
		try {
			resp = client.execute(get);
			HttpEntity entity = resp.getEntity();
			// InputStream input = entity.getContent();
			try {
				entity = new BufferedHttpEntity(entity);
				System.out.println(EntityUtils.toString(entity));
			} finally {
				// if (input != null) {
				// input.close();
				// }
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (resp != null) {
				try {
					resp.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (client != null) {
				try {
					client.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
